package com.xlr.excel.core.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.monitorjbl.xlsx.StreamingReader;
import com.xlr.excel.core.SourseVehicleCoreService;
import com.xlr.excel.entity.SourseVehicle;
import com.xlr.excel.service.SourseVehicleService;
import com.xlr.excel.util.excel.ExportExcel;
import com.xlr.excel.util.excel.ImportExcel;
import com.xlr.excel.util.excel.SheetHandlerData;
import com.xlr.excel.vo.ExcelSourseVo;
import com.xlr.excel.vo.ExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xml.sax.helpers.DefaultHandler;

import javax.servlet.http.HttpServletResponse;
import java.beans.Transient;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: xlr
 * @Date: Created in 下午9:00 2019/2/9
 */
@Service
@Slf4j
public class SourseVehicleCoreServiceImpl implements SourseVehicleCoreService {

    @Autowired
    private SourseVehicleService sourseVehicleService;

    String taskImportTempFilePath = System.getProperty("user.dir")+"/upload/";
    private static Set<String> setMonth = new HashSet <>(  );

    static {
        setMonth.add( "January" );
        setMonth.add( "February" );
        setMonth.add( "March" );
        setMonth.add( "April" );
        setMonth.add( "May" );
        setMonth.add( "June" );
        setMonth.add( "July" );
        setMonth.add( "August" );
        setMonth.add( "September" );
        setMonth.add( "October" );
        setMonth.add( "November" );
        setMonth.add( "December" );
    }

    /**
     * 上传excel
     *
     * @param multipartFile
     * @return
     */
    @Override
    @Async
    public void uploadExcel(MultipartFile multipartFile) throws Exception {
        sourseCore(multipartFile);
    }

    /**
     * @param dimension
     * @param response
     */
    @Override
    public void dowloadExcel(String dimension, HttpServletResponse response) {
        //获取月度数据
        List <ExcelVO> monthSourse = sourseVehicleService.getMonthSourse( dimension );
        //获取季度数据
        List <ExcelVO> quarterSourse = sourseVehicleService.getQuarterSourse( dimension );

        // <ysar,<method,ev>>
        Map<String,Map<String,ExcelSourseVo>> map = new HashMap <>(  );

        if(monthSourse != null && !monthSourse.isEmpty()){
            for (ExcelVO excelVO : monthSourse) {
                getExcelSourseVo(map,excelVO);
            }
        }
        List<ExcelSourseVo> list = new ArrayList <>(  );
        if( map != null && map.size()>0){
            for(String key:map.keySet()){
                Map <String, ExcelSourseVo> yearMap = map.get( key );
                if (yearMap != null && yearMap.size()>0) {
                    for (String s : yearMap.keySet()) {
                        list.add( yearMap.get( s ) );
                    }
                }
            }
        }
        SimpleDateFormat outFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName =  outFormat1.format(new Date()) + ".xlsx";
        try {
            new ExportExcel("CD CONTRACT STATUS", ExcelSourseVo.class, 1).setDataList(list).write(response, fileName)
                    .dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer findCount() {
        int i = sourseVehicleService.selectCount( null );
        return i;
    }

    private void getExcelSourseVo(Map<String,Map<String,ExcelSourseVo>> map ,ExcelVO excelVO){

        Map <String, ExcelSourseVo> yearMap = map.get( excelVO.getYear() );
        if(yearMap == null){
            yearMap = new HashMap <>(  );
        }
        Map excelSourseVoMethod = getExcelSourseVoMethod( yearMap, excelVO );
        map.put( excelVO.getYear(), excelSourseVoMethod);
    }

    public Map<String,ExcelSourseVo> getExcelSourseVoMethod(Map<String,ExcelSourseVo> map,ExcelVO excelVO){

        ExcelSourseVo ev = map.get( excelVO.getMonth() );
        if(ev == null){
            ev = new ExcelSourseVo();
        }
        Integer blank = ev.getBlank();
        Integer active = ev.getActive();
        Integer terminated = ev.getTerminated();
        Integer waived = ev.getWaived();
        ev.setMonth( excelVO.getMonth() );
        ev.setYear( excelVO.getYear() );
        if(0 == excelVO.getMStatus2() ){
            blank += excelVO.getMCount();
        }else if(1 == excelVO.getMStatus2()){
            active += excelVO.getMCount();
        }else if(2 == excelVO.getMStatus2()){
            terminated += excelVO.getMCount();
        }else if(3 == excelVO.getMStatus2()){
            waived += excelVO.getMCount();
        }
        ev.setBlank( blank );
        ev.setActive( active );
        ev.setTerminated( terminated );
        ev.setWaived( waived );
        ev.setYear( excelVO.getYear() );
        map.put( ev.getMonth(),ev );
        return map;
    }

    public void sourseCore(MultipartFile file) throws Exception{
        InputStream inputStream = null;
        String suffixName = file.getOriginalFilename().substring(file.getName().lastIndexOf(".") + 1);
        try {
            File diskfile = new File( taskImportTempFilePath );
            if (!diskfile.exists()) {
                diskfile.mkdirs();
            }
            String path = taskImportTempFilePath.concat( UUID.randomUUID().toString() ).concat( suffixName );
            File xls = new File( path );
            inputStream = file.getInputStream();
            FileUtils.copyInputStreamToFile( inputStream, xls );
            SheetHandlerData shd = new SheetHandlerData(path,12,sourseVehicleService);
            shd.process();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}
